package org.myorg.quickstart;

public class Utils {

    public Utils() {
    }

    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
    }

    public static int ourbytes2Int(byte[] bytes )
    {
        //如果不与0xff进行按位与操作，转换结果将出错，有兴趣的同学可以试一下。
        int int1=bytes[0]&0xff;
        int int2=(bytes[1]&0xff)<<8;
        int int3=(bytes[2]&0xff)<<16;
        int int4=(bytes[3]&0xff)<<24;

        return int1|int2|int3|int4;
    }

    public static int twobytes2Int(byte[] bytes )
    {
        //如果不与0xff进行按位与操作，转换结果将出错，有兴趣的同学可以试一下。
        int int1=bytes[0]&0xff;
        int int2=(bytes[1]&0xff)<<8;

        return int1|int2;
    }

    public static int decompressInteger(byte[] bytes, int byteLength) {
        int value = 0;
        if(byteLength < 0){
            byteLength = bytes.length;
        }
        for (int i = byteLength - 1; i >= 0; i--) {
            for (int bit = 0; bit <= 7; bit++) {
                boolean isSet = ((bytes[i] >>> bit) & 1) == 1;
                if (isSet) {
                    int shift = 8 * (byteLength - 1 - i) + bit;
                    int mask = 1 << shift;
                    value |= mask;
                }
            }
        }
        return value;
    }


}
